import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_rfid_dmo/rfid/model/device_info.dart';
import 'package:flutter_rfid_dmo/rfid/model/rfid_model.dart';
import '../rfid/rfid_connection.dart';
import 'scan_page.dart';

class RFIDPage extends StatefulWidget {
  const RFIDPage({Key? key}) : super(key: key);

  @override
  State<RFIDPage> createState() => _RFIDPageState();
}

class _RFIDPageState extends State<RFIDPage>
    with AutomaticKeepAliveClientMixin {
  final RFIDConnection _rfidService = RFIDConnection();

  // 标签操作参数
  final TextEditingController _epcController = TextEditingController();
  final TextEditingController _dataController = TextEditingController();

  final List<String> _logs = [
    'Start !',
  ];

  // 颜色常量
  static const Color kButtonColor = Color(0xFFF2F2F2); // 按钮灰色
  static const Color kLogTextColor = Color(0xFFE91E63); // 粉色
  static const Color kSystemBarColor = Colors.black; // 系统消息黑色
  StreamSubscription<RfidResult>? _rfidMsgSub;

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();
    _initializeRFID();
  }

  @override
  void dispose() {
    _epcController.dispose();
    _dataController.dispose();
    _rfidService.onDispose();
    _rfidMsgSub?.cancel();
    super.dispose();
  }

  _updateState() {
    if (mounted) {
      setState(() {});
    }
  }

  _onStateChange(bool connected) {
    if (connected) {
      _addLog('设备已连接');
      _readDeviceInfo();
    } else {
      _addLog('设备已断开');
    }
  }

  void _initializeRFID() {
    _rfidService.initialize(_onStateChange);
    // 添加消息处理回调
    _rfidMsgSub = _rfidService.resultStream.listen((result) {
      switch (result.type) {
        case RfidResultType.deviceInfo:
          RfidDeviceInfo info = result.data;
          // 处理设备信息
          _addLog(info.getInfoString());
          break;
        case RfidResultType.batteryInfo:
          var battery = result.data;
          // 处理电池信息
          _addLog(battery.toString());
          break;
        default:
          if (result.data != null) {
            _addLog(result.data.toString());
          }
          break;
      }
      log("result: ${result.type} ${result.data} ${result.message}");
    });
  }

  Future<void> _readDeviceInfo() async {
    _addLog('读取设备信息...');
    await _rfidService.readDeviceInfo();
    await Future.delayed(const Duration(milliseconds: 500));
    await _rfidService.readBat();
    _updateState();
  }

  void _startScan() async {
    final device = await Navigator.push(
      context,
      MaterialPageRoute(builder: (_) => const ScanPage()),
    );
    if (device != null) {
      _addLog('已选择设备: ${device.platformName} ${device.remoteId}');
    }
  }

  void _disconnect() async {
    await _rfidService.disconnect();
    _addLog('蓝牙已断开');
  }

  void _clearLogs() {
    setState(() {
      _logs.clear();
    });
  }

  void _addLog(String log) {
    setState(() {
      _logs.add(log);
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用super.build
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 四个大按钮
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: GridView.count(
              crossAxisCount: 2,
              shrinkWrap: true,
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
              childAspectRatio: 2.8,
              physics: const NeverScrollableScrollPhysics(),
              children: [
                _buildBigButton('连接', _startScan),
                _buildBigButton('断开', _disconnect),
                _buildBigButton('读设备状态', _readDeviceInfo),
                _buildBigButton('清除列表', _clearLogs),
              ],
            ),
          ),
          // 黑色系统消息栏
          Container(
            color: kSystemBarColor,
            width: double.infinity,
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: const Center(
              child: Text(
                '系统消息',
                style: TextStyle(color: Colors.white, fontSize: 18),
              ),
            ),
          ),
          // 日志/设备信息区
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(12),
              child: Text(
                _logs.join('\n'),
                style: const TextStyle(
                  color: kLogTextColor,
                  fontSize: 16,
                  height: 1.4,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 大按钮构建方法
  Widget _buildBigButton(String text, VoidCallback onPressed) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: kButtonColor,
        foregroundColor: Colors.black,
        textStyle: const TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        elevation: 0,
      ),
      onPressed: onPressed,
      child: Center(child: Text(text)),
    );
  }
}
